import React, { FC, useEffect, useState } from "react"
import { Typography } from "antd"
import { useRequest } from "ahooks"
import { getComponentStatService } from "../../../../services/stat"
import { useParams } from "react-router-dom"
import { getComponentConfigByType } from "../../../../components/QuestionComponents"
// import PieDemo from "./PieDemo"
// import BarDemo from "./BarDemo"

const { Title } = Typography

type PropsType = {
    selectedComponentId: string
    selectedComponentType: string
}

const ChartStat: FC<PropsType> = (props: PropsType) => {
    const { selectedComponentId, selectedComponentType } = props
    const { id = "" } = useParams()

    // 存储请求到的数据
    const [stat, setStat] = useState([])

    const { run } = useRequest(async (questionId, componentId) => await getComponentStatService(questionId, componentId), {
        // 手动调用
        manual: true,
        // res 就是 异步函数的返回结果
        onSuccess(res) {
            setStat(res.stat)
        }
    })

    useEffect(() => {
        // 给 run 传递的参数会被传递到 useRequest 里面的异步函数中
        // 选中组件了才执行axios请求，否则就不请求
        if (selectedComponentId) run(id, selectedComponentId)
    }, [id, selectedComponentId])

    // 生成图表信息，防止没有选中
    function genStatElem() {
        if (!selectedComponentId) return <div>请先选择组件</div>

        // 根据类型获取组件对应的统计组件
        const { StatComponent } = getComponentConfigByType(selectedComponentType) || {}
        // 可能不存在
        if (StatComponent == null) return <div>该组件无统计图表</div>

        return <StatComponent stat={stat} />
    }

    return (
        <>
            <Title level={3}>图表统计</Title>
            <div>{genStatElem()}</div>
        </>
    )
}

export default ChartStat
